/* eslint-disable function-paren-newline */
import React, { Component } from 'react';
import fetch from 'dva/fetch';
import { Form, Row, Col, Button, List, Card, Checkbox, Icon, Select } from 'antd';
import ShowType from '../../../routes/common/showType';
// import * as commonFunc from '../../Common/commonFunc';
import styles from '../../../index.less';
import * as config from '../../../utils/config';

const FormItem = Form.Item;
const { Option } = Select;

class TabMainTableComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sTabId: props.app.currentPane.key, /* 当前标签 */
      componentName: props.componentName, /* 组件名 */
      masterConfig: props.masterConfig, /* 配置 */
      // mainConfig: props.mainConfig, /* 表配置 */
      // loading: false,
      // formData: props.formData,
      sId: props.sId, /* 业务数据Id */
      dataList: [], /* 数据 */
      sActiveId: props.sActiveId, /* 窗体Id */
      disabled: props.disabled, /* 是否是查看状态 */
      sType: '', /* 类型 */
      sBillNo: '', /* 工单编号 */
      sCustomerId: '', /* 客户名称 */
      // sProductClassifyId: '', /* 印件分类名称 */
      sProductId: '', /* 印件名称 */
      sManualNo: '', /* 手工单号 */
      sContacts: '', /* 联系人 */
      sProductStyle: '', /* 规格 */
      sMakePerson: '', /* 制单人 */
      sPhone: '', /* 联系电话 */
      dProductQty: '', /* 数量 */
      tCreateDate: '', /* 制单日期 */
      sMaterialsName: '', /* 纸张 */
      iPrintModePo: '', /* 印刷颜色 单双面 */
      dSumPQty: '', /* P数 */
      iPositiveColor: '', /* 印刷颜色 */
      // sBackProcessClassify: '', /* 后道工艺分类 */
      sBackProcess: '', /* 后道工艺 */
      sBackProcessData: [], /* 后道工艺数据 */
      // reserveContent: '',
      expand: false,
    };
  }

  componentWillMount() {
    /* 获取主表数据 */
    const {
      masterConfig, sId, sActiveId, componentName, sTabId,
    } = this.state;
    const { dispatch } = this.props;
    if (sId !== undefined && sId !== '') {
      const mainId = masterConfig.sId;
      /* 表Id */
      const value = { sId, pageSize: '', pageNum: '' };
      /* 业务数据Id */
      const dataUrl = `${config.server_host}business/getBusinessDataByFormcustomId/${mainId}?sModelsId=${sActiveId}`;
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: dataUrl, sTabId, componentName, value, formRoute: '/workorder', returnType: 'data',
        },
      });
      /* 获取主表数据 */
    } else if (sId === '' && this.props.newIdFlag) {
      const url = `${config.server_host}getUuid/${this.props.newIdlength}`;
      dispatch({
        type: 'content/getCopyDataId',
        payload: {
          sTabId, url, formRoute: '/workorder', componentName,
        },
      });
    }
    if (masterConfig.gdsconfigformslave !== undefined) {
      /* 工单主表配置 */
      const mainConfig = masterConfig.gdsconfigformslave;
      this.setState({
        sId: sId !== undefined ? sId : '',
        sType: mainConfig.filter(item => (item.sName.toLowerCase() === 'stype'))[0],
        sBillNo: mainConfig.filter(item => (item.sName.toLowerCase() === 'sbillno'))[0],
        sCustomerId: mainConfig.filter(item => (item.sName.toLowerCase() === 'scustomerid'))[0],
        sProductId: mainConfig.filter(item => (item.sName.toLowerCase() === 'sproductid'))[0],
        sManualNo: mainConfig.filter(item => (item.sName.toLowerCase() === 'smanualno'))[0],
        sContacts: mainConfig.filter(item => (item.sName.toLowerCase() === 'scontacts'))[0],
        sProductStyle: mainConfig.filter(item => (item.sName.toLowerCase() === 'sproductstyle'))[0],
        sMakePerson: mainConfig.filter(item => (item.sName.toLowerCase() === 'smakeperson'))[0],
        sPhone: mainConfig.filter(item => (item.sName.toLowerCase() === 'sphone'))[0],
        dProductQty: mainConfig.filter(item => (item.sName.toLowerCase() === 'dproductqty'))[0],
        tCreateDate: mainConfig.filter(item => (item.sName.toLowerCase() === 'tcreatedate'))[0],
        sMaterialsName: mainConfig.filter(item => (item.sName.toLowerCase() === 'smaterialsname'))[0],
        iPrintModePo: mainConfig.filter(item => (item.sName.toLowerCase() === 'iprintmodepo'))[0],
        dSumPQty: mainConfig.filter(item => (item.sName.toLowerCase() === 'dsumpqty'))[0],
        iPositiveColor: mainConfig.filter(item => (item.sName.toLowerCase() === 'ipositivecolor'))[0],
        sBackProcess: mainConfig.filter(item => (item.sName.toLowerCase() === 'sbackprocess'))[0],
        // sBackProcessClassify: mainConfig.filter(item => (item.sName.toLowerCase() === 'sbackprocessclassify'))[0],
        bBillOutside: mainConfig.filter(item => (item.sName.toLowerCase() === 'bbilloutside'))[0],
      });
    }
  }

  componentDidMount() {
    const { token } = this.props.app;
    const { sActiveId, sBackProcess } = this.state;
    const url = `${config.server_host}business/getSelectDataBysControlId/${sBackProcess.sId}?sModelsId=${sActiveId}`;
    const values = {
      sKeyUpFilterName: '',
      sSqlCondition: {},
    };
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(values),
    };

    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const { rows } = json.dataset;
        this.setState({ sBackProcessData: rows });
      }
    });
  }

  componentWillReceiveProps(nextProps) {
    const {
      sId, disabled, content, dataSet,
    } = nextProps;
    const { dataList } = content;
    const {
      sDataListTabId, returnType, urlData, loading, componentName,
    } = dataList;
    this.setState({ disabled, dataList: dataSet });
    if (this.state.sTabId === sDataListTabId && this.state.sTabId === nextProps.app.currentPane.key
      && this.state.componentName === componentName) {
      if (loading) return;
      if (returnType === 'data') {
        this.setState({
          dataList: urlData,
          sId: sId !== undefined ? sId : '',
        });
      }
      this.setState({ sId });
    }
    const mainConfig = this.state.masterConfig.gdsconfigformslave;
    if (Object.keys(mainConfig).length > 0) {
      // const { sActiveId, app, form } = nextProps;
      // const childProps = {
      //   app, form, sActiveId, sId, dataList, disabled,
      // };
      // const reserveContent = commonFunc.Reserve(mainConfig, childProps);
      // this.setState({ reserveContent });
    }
  }

  shouldComponentUpdate(nextProps) {
    const { componentName } = nextProps;
    let flag = true;
    if (nextProps.disabled !== this.state.disabled) {
      return true;
    }
    if (this.state.sTabId === nextProps.app.currentPane.key &&
      this.state.componentName === componentName) {
      flag = true;
    } else {
      flag = false;
    }
    return flag;
  }

  handleChange = (e, value, sPartsName) => {
    this.props.handleGyChange(e, value, sPartsName);
  };

  handleToggle = () => {
    const { expand } = this.state;
    this.setState({ expand: !expand });
  };

  handleA = (sId) => {
    const { sBackProcessData } = this.state;
    const data = sBackProcessData.filter(item => item.sParentId === sId);
    const optionProcess = [];
    data.forEach((item) => {
      optionProcess.push(<Option key={item.sId} value={item.sId} data-recordrow={item}>{item.sProcessName}</Option>);
    });
    return optionProcess;
  }

  handleSelectChangeProcess = (sAssignField, value, option) => {
    const { dataName, dataType } = this.props;
    if (sAssignField !== undefined) {
      // 这一段是处理工序的赋值字段，原因工序是动态生成，没用showtype
      const resultFields = [];
      const sAssignFields = sAssignField.split(',');
      const recordRow = option.props['data-recordrow'];
      sAssignFields.map((item) => {
        const itemsplits = item.split(':');
        return resultFields.push({ key: itemsplits[0], value: recordRow[itemsplits[1]] });
      });
      value = resultFields;
    }
    this.props.handleSelectChange(value, dataType, dataName);
  }

  render() {
    const {
      app, form, dataName, handleModalPane, dataType, handleSelectChange, handleDataCreate, handleCalculate, gyCards, dataSet, sBackProcessClassifyData,
    } = this.props;
    const { getFieldDecorator } = form;
    const {
      sActiveId, dataList, sId, disabled, expand,
    } = this.state;
    const {
      sType, sBillNo, sCustomerId, sProductId, sManualNo,
      sContacts, sProductStyle, sMakePerson, sPhone, dProductQty,
      tCreateDate, sMaterialsName, iPrintModePo, iPositiveColor, dSumPQty,
      bBillOutside,
    } = this.state;
    const childProps = {
      app,
      form,
      sActiveId,
      dataList,
      sId,
      disabled,
      dataName,
      dataType,
      handleModalPane,
      handleSelectChange,
    };
    const { sAllPartsName } = dataSet;
    let allPartsName = [];
    if (sAllPartsName !== undefined) {
      allPartsName = sAllPartsName.split(',');
    }
    const sTypeProps = { showConfig: sType, ...childProps };
    const sBillNoProps = { showConfig: sBillNo, ...childProps };
    const sCustomerIdProps = { showConfig: sCustomerId, ...childProps };
    const sProductIdProps = { showConfig: sProductId, ...childProps };
    const sManualNoProps = { showConfig: sManualNo, ...childProps };
    const sContactsProps = { showConfig: sContacts, ...childProps };
    const sProductStyleProps = { showConfig: sProductStyle, ...childProps };
    const sMakePersonProps = { showConfig: sMakePerson, ...childProps };
    const sPhoneProps = { showConfig: sPhone, ...childProps };
    const dProductQtyProps = { showConfig: dProductQty, ...childProps };
    const tCreateDateProps = { showConfig: tCreateDate, ...childProps };
    // const sMaterialsNameProps = { showConfig: sMaterialsName, ...childProps };
    // const iPrintModePoProps = { showConfig: iPrintModePo, ...childProps };
    // const iPositiveColorProps = { showConfig: iPositiveColor, ...childProps };
    const bBillOutsideProps = { showConfig: bBillOutside, ...childProps };
    const halfformItemLayout = { labelCol: { span: 7 }, wrapperCol: { span: 16 } };
    return (
      <FormItem className={styles.searchMainForm}>
        <Row>
          <div className={styles.workeOrderMainT}>
            生产施工单
          </div>
          <div className={styles.workOrderMain}>
            <Button onClick={handleCalculate}>计算</Button>
            <ShowType sName="bBillOutside" showDefaultName="整单发外" {...bBillOutsideProps} />
          </div>
        </Row>
        <Row type="flex">
          <Col
            span={6}
            order={sType.iOrder > 24 ? 24 : sType.iOrder}
            style={{ display: sType.bVisible ? 'block' : 'none' }}
          >
            <ShowType sName="sType" showDefaultName="类型" {...sTypeProps} />
          </Col>
          <Col
            span={6}
            order={sBillNo.iOrder > 24 ? 24 : sBillNo.iOrder}
            style={{ display: sBillNo.bVisible ? 'block' : 'none' }}
          >
            <ShowType sName="sBillNo" showDefaultName="工单编号" {...sBillNoProps} />
          </Col>
          <Col
            span={6}
            order={sCustomerId.iOrder > 24 ? 24 : sCustomerId.iOrder}
            style={{ display: sCustomerId.bVisible ? 'block' : 'none' }}
          >
            <ShowType sName="sCustomerId" showDefaultName="客户名称" {...sCustomerIdProps} />
          </Col>
          <Col
            span={6}
            order={sProductId.iOrder > 24 ? 24 : sProductId.iOrder}
            style={{ display: sProductId.bVisible ? 'block' : 'none' }}
          >
            <ShowType sName="sProductId" showDefaultName="印件名称" {...sProductIdProps} />
          </Col>
          <Col
            span={6}
            order={sManualNo.iOrder > 24 ? 24 : sManualNo.iOrder}
            style={{ display: sManualNo.bVisible ? 'block' : 'none' }}
          >
            <ShowType sName="sManualNo" showDefaultName="手工单号" {...sManualNoProps} />
          </Col>
          <Col
            span={6}
            order={sContacts.iOrder > 24 ? 24 : sContacts.iOrder}
            style={{ display: sContacts.bVisible ? 'block' : 'none' }}
          >
            <ShowType sName="sContacts" showDefaultName="联系人" {...sContactsProps} />
          </Col>
          <Col
            span={6}
            order={sProductStyle.iOrder > 24 ? 24 : sProductStyle.iOrder}
            style={{ display: sProductStyle.bVisible ? 'block' : 'none' }}
          >
            <ShowType sName="sProductStyle" showDefaultName="规格" {...sProductStyleProps} />
          </Col>
          <Col
            span={6}
            order={sMakePerson.iOrder > 24 ? 24 : sMakePerson.iOrder}
            style={{ display: sMakePerson.bVisible ? 'block' : 'none' }}
          >
            <ShowType sName="sMakePerson" showDefaultName="制单人" {...sMakePersonProps} />
          </Col>
          <Col
            span={6}
            order={sPhone.iOrder > 24 ? 24 : sPhone.iOrder}
            style={{ display: sPhone.bVisible ? 'block' : 'none' }}
          >
            <ShowType sName="sPhone" showDefaultName="联系电话" {...sPhoneProps} />
          </Col>
          <Col
            span={6}
            order={dProductQty.iOrder > 24 ? 24 : dProductQty.iOrder}
            style={{ display: dProductQty.bVisible ? 'block' : 'none' }}
          >
            <ShowType sName="dProductQty" showDefaultName="数量" {...dProductQtyProps} />
          </Col>
          <Col
            span={6}
            order={tCreateDate.iOrder > 24 ? 24 : tCreateDate.iOrder}
            style={{ display: tCreateDate.bVisible ? 'block' : 'none' }}
          >
            <ShowType sName="tCreateDate" showDefaultName="制单日期" {...tCreateDateProps} />
          </Col>
        </Row>
        <button className={styles.collapseA} onClick={this.handleToggle}>
          <span>生产施工单</span><Icon type={expand ? 'up' : 'down'} />
        </button>
        {allPartsName.length > 0 ?
          <List
            grid={{ column: 6 }}
            dataSource={allPartsName}
            size="small"
            className={styles.workerList}
            renderItem={(sPartsName, i) => (
              <Row style={{ height: expand ? 'auto' : '0', overflow: 'hidden' }}>
                <Col className={styles.sPartsName}>
                  <span>{sPartsName}</span>
                </Col>
                <Row className={styles.collapseWorker}>
                  <Col
                    span={6}
                    order={dSumPQty.iOrder > 24 ? 24 : dSumPQty.iOrder}
                    style={{ display: dSumPQty.bVisible ? 'block' : 'none' }}
                  >
                    <ShowType
                      sName={`dSumPQty${sPartsName}`}
                      showDefaultName="P数"
                      {...childProps}
                      showConfig={{ ...dSumPQty, sName: `dSumPQty${sPartsName}` }}
                    />
                  </Col>

                  <Col
                    span={6}
                    order={sMaterialsName.iOrder > 24 ? 24 : sMaterialsName.iOrder}
                    style={{ display: sMaterialsName.bVisible ? 'block' : 'none' }}
                  >
                    <ShowType
                      sName={`sMaterialsName${sPartsName}`}
                      showDefaultName="纸张"
                      {...childProps}
                      showConfig={{ ...sMaterialsName, sName: `sMaterialsName${sPartsName}`, sAssignField: sMaterialsName.sAssignField.replace(/:/g, `${sPartsName}:`) }}
                    />
                  </Col>
                  <Col
                    span={10}
                    order={iPrintModePo.iOrder > 24 ? 24 : iPrintModePo.iOrder}
                    style={{ display: iPrintModePo.bVisible ? 'block' : 'none' }}
                  >
                    <Row>
                      <Col span={14}>
                        <ShowType
                          sName={`iPrintModePo${sPartsName}`}
                          showDefaultName="印刷方式"
                          {...childProps}
                          showConfig={{ ...iPrintModePo, sName: `iPrintModePo${sPartsName}`, sAssignField: iPrintModePo.sAssignField.replace(/:/g, `${sPartsName}:`) }}
                          formItemLayout={halfformItemLayout}
                        />
                      </Col>
                      <Col span={9}>
                        <ShowType
                          sName={`iPositiveColor${sPartsName}`}
                          showDefaultName="颜色"
                          {...childProps}
                          showConfig={{ ...iPositiveColor, sName: `iPositiveColor${sPartsName}`, sAssignField: iPositiveColor.sAssignField.replace(/:/g, `${sPartsName}:`) }}
                          labelNo
                        />
                      </Col>
                    </Row>
                  </Col>
                  {i === 0 ?
                    <div className={styles.workOrderMain}>
                      <Button onClick={handleDataCreate}>生成数据</Button>
                    </div> : ''
                  }
                </Row>
                <Row>
                  <Col>
                    {sBackProcessClassifyData !== '' ?
                      <List
                        grid={{ column: 6 }}
                        dataSource={sBackProcessClassifyData.filter(item => (item.sType !== '3' && (item.sPartsName === sPartsName || item.sPartsName === '')))}
                        size="small"
                        className={styles.workerList}
                        renderItem={item => (
                          <List.Item className={styles.workerListItem}>
                            <Card>
                              <Checkbox
                                checked={gyCards !== undefined && gyCards.filter(card => (card.sId === item.sId && card.sPartsName === sPartsName)).length > 0}
                                onChange={(e) => {
                                  this.handleChange(e, item, sPartsName);
                                }}
                                title={item}
                              >
                                {item.sName}
                              </Checkbox>
                              <div id="sPartsName">
                                {gyCards !== undefined && gyCards.filter(card => (card.sId === item.sId && card.sPartsName === sPartsName)).length > 0 ?
                                  <FormItem>
                                    {getFieldDecorator(`${item.sId + sPartsName}`, {
                                    })(
                                      <Select
                                        showSearch
                                        filterOption={(input, option) =>
                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                        onSelect={this.handleSelectChangeProcess.bind(this, `${item.sId + sPartsName}:sId,${item.sId + item.sName + sPartsName}:sProcessName,${item.sId + item.sType + sPartsName}:sType`)}
                                      >
                                        {this.handleA(item.sId)}
                                      </Select>)}
                                  </FormItem>
                                  : ''}
                              </div>
                            </Card>
                          </List.Item>
                        )}
                      />
                    : ''}
                  </Col>
                </Row>
              </Row>
            )}
          />
          : ''}
        {allPartsName.length > 0 ?
          <Row style={{ height: expand ? 'auto' : '0', overflow: 'hidden' }}>
            <Col className={styles.sPartsName}>
              <span>成品工序</span>
            </Col>
            <Col className={styles.collapseWorker}>
              {sBackProcessClassifyData !== '' ? // 成品工序部分
                <List
                  grid={{ column: 6 }}
                  dataSource={sBackProcessClassifyData.filter(item => (item.sType === '3'))}
                  size="small"
                  className={styles.workerList}
                  renderItem={item => (
                    <List.Item className={styles.workerListItem}>
                      <Card >
                        <Checkbox
                          onChange={(e) => {
                            this.handleChange(e, item, '');
                          }}
                          title={item}
                        >{item.sName}
                        </Checkbox>
                        <div id="sPartsName">
                          {gyCards !== undefined && gyCards.filter(card => (card.sId === item.sId)).length > 0 ?
                            <FormItem>
                              {getFieldDecorator(`${item.sId}`, {
                              })(
                                <Select
                                  showSearch
                                  filterOption={(input, option) =>
                                  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                  onSelect={this.handleSelectChangeProcess.bind(this, `${item.sId}:sId,${item.sId + item.sName}:sProcessName`)}
                                >
                                  { this.handleA(item.sId) }
                                </Select>)}
                            </FormItem>
              : ''}
                        </div>
                      </Card>
                    </List.Item>
              )}
                />
            : ''}
            </Col>
          </Row>
          : ''}
      </FormItem>
    );
  }
}

export default TabMainTableComponent;
